/*
 * File:    For.java
 * Created: 20-Feb-2009
 * Version: $Id$
 *
 * COPYRIGHT (C) 2009, Bitgate Mobile, LLC.  All Rights Reserved.
 *
 * software@bitgatemobile.com
 */

package com.webplasm.render.tags.u;

import java.util.Arrays;
import java.util.List;

import com.webplasm.context.RenderContext;
import com.webplasm.render.engine.RenderException;
import com.webplasm.render.tags.TagInterface;
import com.webplasm.render.tags.WrappedNode;
import com.webplasm.store.VariableStoreInterface;
import com.webplasm.store.VariableContainer.VariableType;

/**
 * Performs iterative stepping of a variable from an initial point to a termination point.  This is the same
 * functionality that Java provides with the &quot;for&quot; function.
 * 
 * @author kenji
 * @since Webplasm 1.0
 */
public class For extends WrappedNode implements TagInterface {
	private static final String DESCRIPTION = "Provides a numeric iterator function for repetitive rendering.";

	public String getNamespace() {
		return "u";
	}
	
	public List<String> getAttributes() {
		return Arrays.asList("var", "init", "term", "step");
	}
	
	public List<String> getManagedNodes() {
		return null;
	}

	public String getDescription() {
		return DESCRIPTION;
	}

	@Override
	public StringBuffer render(RenderContext rContext) throws RenderException {
		if (elements.get("var") == null) {
			throw new RenderException("u:for requires a variable for iteration assignment.");
		}
		
		if (elements.get("init") == null) {
			throw new RenderException("u:for requires an initial iteration value.");
		}
		
		if (elements.get("term") == null) {
			throw new RenderException("u:for requires a termination iteration value.");
		}
		
		int directionStep = 1;
		int startValue = Integer.parseInt(getWrappedAttribute(rContext, "init"));
		int endValue = Integer.parseInt(getWrappedAttribute(rContext, "term"));
		
		if (elements.get("step") != null) {
			directionStep = Integer.parseInt(getWrappedAttribute(rContext, "step"));
		}
		
		VariableStoreInterface vsInterface = rContext.getVariableStore().getVariable(elements.get("var"), VariableType.INTEGER);
		StringBuffer buf = new StringBuffer();
		
		if (endValue < startValue) {
			for(int i = startValue; i > (endValue - 1); i -= directionStep) {
				vsInterface.setValue(Integer.toString(i));
				buf.append(super.render(rContext));
			}
		} else {
			for(int i = startValue; i < (endValue + 1); i += directionStep) {
				vsInterface.setValue(Integer.toString(i));
				buf.append(super.render(rContext));
			}
		}
	
		return buf;
	}
}